import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 参数1：仓库的名字
 * 参数2：写仓库逻辑代码部分（推荐组合式api）
 * 参数3：持久化
 */
export const useCartStore = defineStore(
  'cart',
  () => {
    // state
    const cartList = ref([])

    // getters
    const getTotalPrice = computed(() =>
      cartList.value
        .filter(item => item.checked)
        .reduce((total, item) => total + item.num * item.price, 0)
    )

    const isAllChecked = computed(() =>
      cartList.value.every(item => item.checked)
    )

    // mutations
    const addToCart = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.num += goods.num
      } else {
        cartList.value.push(goods)
      }
    }

    // 更改商品选中状态
    const updateGoodsState = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.checked = goods.checked
      }
    }

    // 更改商品选中数量
    const updateGoodsNum = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.num = goods.num
      }
    }

    // 删除商品
    const deleteGoodsById = proid => {
      setTimeout(() => {
        cartList.value = cartList.value.filter(item => item.proid !== proid)
      }, 0)
    }

    // 全选 & 反选
    const allCheckedOrNot = checked => {
      cartList.value.forEach(item => {
        item.checked = checked
      })
    }

    return {
      cartList,
      addToCart,
      getTotalPrice,
      updateGoodsState,
      updateGoodsNum,
      deleteGoodsById,
      isAllChecked,
      allCheckedOrNot
    }
  },
  {
    persist: true
  }
)
